package com.zlj.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 * 从application中获取map
 * 从Request中得到当前的客户端中的IP
 * 进行统计工作，结果保存到Map中
 * 
 * @author bashen
 *
 */
@WebFilter(filterName = "FilterDemo",urlPatterns="/*")
public class FilterDemo implements Filter {

	private FilterConfig config;
	
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		//获取ServletContext
		ServletContext application = config.getServletContext();
		
		//得到ServletContext中的map
		Map<String,Integer> map = (Map<String, Integer>) application.getAttribute("map");
		
		//从Request中获取当前客户端的IP
		String ip = request.getRemoteAddr();
		
		if(map.containsKey(ip)) {  //如果ip在map中存在，说明不是第一次访问
			Integer count = map.get(ip);
			map.put(ip, count + 1);
		} else {     //如果ip在map中不存在，说明是第一次访问
			map.put(ip, 1);
		}
		
		//把map再放回到ServletContext中
		application.setAttribute("map", map);
		
		chain.doFilter(request, response);
	}

	/**
	 * 服务器启动时就执行，并且只执行一次
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		this.config = fConfig;
	}
}
